package fr.ece.ing4.chatapplication.client;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created by dudu on 27/03/14.
 */
public class PopupFrame extends JFrame implements ActionListener {

    private JLabel label;
    private JTextField text;
    private JButton ok, quit;
    private JPanel buttons;
    private ClientController clientController;

    private void initComponents() {

        label = new JLabel();
        text = new JTextField();
        ok = new JButton("OK");
        quit = new JButton("Quit/Cancel");
        buttons = new JPanel();
        buttons.setLayout(new BoxLayout(buttons, BoxLayout.LINE_AXIS));
    }

    private void setComponentsProperties() {

        this.setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));

    }

    private void addComponentsListener() {

        ok.addActionListener(this);
        quit.addActionListener(this);
    }

    private void addComponentsWithConstraints(){

        this.add(label);
        this.add(text);

        buttons.add(ok);
        buttons.add(quit);

        this.add(buttons);
    }

    public PopupFrame(String title, String message, ClientController clientController) {

        initComponents();
        setComponentsProperties();
        addComponentsListener();
        addComponentsWithConstraints();

        this.clientController = clientController;
        this.setTitle(title);
        label.setText(message);

        this.setSize(new Dimension(250, 100));
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if ( e.getSource() == ok ) {
            if (this.getTitle() == "Choose Username") {

                if (text.getText().equals("")) {
                    clientController.setClientName("GUEST");
                    clientController.init();
                }
                else {
                clientController.setClientName(text.getText());
                clientController.init();
                }
            }
            else if (this.getTitle() == "Enter Chatroom Name") {
                clientController.createChatRoom(text.getText());
            }
            this.dispose();

        } else if (e.getSource() == quit ) {
            if (this.getTitle() == "Choose Username") {

                System.exit(0);
            }
            else if (this.getTitle() == "Enter Chat Room Name") {

                this.dispose();
            }


        }


    }
}
